package com.wjc.train.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wjc.train.business.entity.Station;
import com.wjc.train.business.repository.StationRepository;
import com.wjc.train.business.req.StationQueryReq;
import com.wjc.train.business.req.StationSaveReq;
import com.wjc.train.business.resp.StationQueryResp;
import com.wjc.train.business.service.IStationService;
import com.wjc.train.common.enums.LogicEnum;
import com.wjc.train.common.exception.BusinessException;
import com.wjc.train.common.untils.CopyUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 车站表 服务实现类
 * </p>
 *
 * @author Guessed
 * @since 2023-07-31
 */
@Service
public class StationServiceImpl  implements IStationService {

    @Resource
    private StationRepository stationRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(StationSaveReq stationSaveReq) {
        //校验站名是否相同
        Station dbStation =
                stationRepository.getOne(new QueryWrapper<Station>()
                            .eq("name", stationSaveReq.getName())
                            .eq("is_deleted",LogicEnum.NOT_DELETED.getCode()));
        if(ObjectUtil.isNotEmpty(dbStation)){
            throw new BusinessException("该站已存在");
        }
        Station station = CopyUtil.copy(stationSaveReq, Station.class);
        stationRepository.saveOrUpdate(station);
    }

    @Override
    public IPage<StationQueryResp> queryList(IPage<StationQueryResp> page, StationQueryReq stationQueryReq) {
        return stationRepository.queryList(page,stationQueryReq);
    }

    @Override
    public void delete(Long id) {
        stationRepository.getBaseMapper().deleteById(id);
    }

    @Override
    public List<StationQueryResp> queryAll() {
        List<Station> list = stationRepository.lambdaQuery()
                                                .eq(Station::getIsDeleted, LogicEnum.NOT_DELETED.getCode())
                                                .list();
        return CopyUtil.copyList(list,StationQueryResp.class);
    }
}
